<template>
	<view class="container">
		<!-- 空白页 -->
		<view v-if="!isLogin || empty === true" class="empty">
			<view class="empty-content">
				<view class="empty-icon">
					<uni-icons type="cart" size="120" color="#e0e0e0"></uni-icons>
				</view>
				<view class="empty-title" v-if="isLogin">
					购物车空空如也
				</view>
				<view class="empty-title" v-else>
					请先登录
				</view>
				<view class="empty-subtitle" v-if="isLogin">
					快去挑选心仪的商品吧
				</view>
				<view class="empty-subtitle" v-else>
					登录后查看购物车商品
				</view>
				<view class="empty-actions">
					<button v-if="isLogin" class="empty-btn primary" @click="navToHome">
						<uni-icons type="home" size="18" color="#fff" style="margin-right: 8rpx;"></uni-icons>
						随便逛逛
					</button>
					<button v-else class="empty-btn primary" @click="navToLogin">
						<uni-icons type="person" size="18" color="#fff" style="margin-right: 8rpx;"></uni-icons>
						去登录
					</button>
				</view>
			</view>
		</view>
		<view v-else class="cart-content">
			<!-- 购物车头部 -->
			<view class="cart-header">
				<view class="header-title">
					<text>商品数({{cartList.length}})</text>
				</view>
				<view class="header-actions" v-if="allChecked" @click="clearCart">
					<uni-icons type="trash" size="18" color="#999"></uni-icons>
					<text>清空</text>
				</view>
			</view>
			
			<!-- 列表 -->
			<view class="cart-list">
				<block v-for="(item, index) in cartList" :key="item.id">
					<view
						class="cart-item" 
						:class="{'b-b': index!==cartList.length-1, 'checked': item.checked}"
					>
						<view class="item-checkbox" @click="check('item', index)">
							<view class="checkbox-circle" :class="{checked: item.checked}">
								<uni-icons v-if="item.checked" type="checkmarkempty" size="14" color="#fff"></uni-icons>
							</view>
						</view>
						
						<view class="item-image" @click="navToProduct(item.goods_id)">
							<image :src="item.images" mode="aspectFill" class="product-img"></image>
						</view>
						
						<view class="item-content">
							<view class="item-header">
								<text class="item-title" @click="navToProduct(item.goods_id)">{{item.title}}</text>
								<view class="item-delete" @click="deleteCartItem(index)">
									<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
								</view>
							</view>
							
							<view class="item-attrs" v-if="item.rule_text">
								<text class="attr-text">{{item.rule_text}}</text>
							</view>
							
							<view class="item-footer">
								<view class="item-price">
									<text class="price-symbol">¥</text>
									<text class="price-value">{{item.price}}</text>
								</view>
								
								<view class="item-quantity">
									<uni-number-box 
										:min="1"
										:value="item.goods_num"
										:index="index"
										@change="numberChange($event, index)"
									></uni-number-box>
								</view>
							</view>
						</view>
					</view>
				</block>
			</view>
			
			<uni-load-more :status="loadingType" v-if="showLoad"></uni-load-more>
			
			<!-- 底部菜单栏 -->
			<view class="action-section">
				<view class="select-all" @click="check('all')">
					<view class="checkbox-circle" :class="{checked: allChecked}">
						<uni-icons v-if="allChecked" type="checkmarkempty" size="14" color="#fff"></uni-icons>
					</view>
					<text class="select-text">全选</text>
				</view>
				
				<view class="total-box">
					<view class="total-info">
						<text class="total-label">合计：</text>
						<text class="total-price">
							<text class="price-symbol">¥</text>
							<text class="price-value">{{total}}</text>
						</text>
					</view>
					<view class="save-info" v-if="selectedCount > 0">
						<text>已选{{selectedCount}}件</text>
					</view>
				</view>
				
				<button type="primary" class="confirm-btn" :class="{disabled: selectedCount === 0}" @click="createOrder">
					去结算({{selectedCount}})
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		goLogin,
		checkLogin
	} from '@/libs/login';
	import { onTabPageShow } from '@/utils/tabbar.js';
	
	export default {
		
		data() {
			return {
				showLoad: true,
				total: 0, // 总价格
				allChecked: false, // 全选状态  true|false
				empty: false, // 空白页现实  true|false
				cartList: [],
				isLogin: false,
				limit: 10,
				nowPage: 0,
				pages: 1,
				loadingType: 'more' // 加载更多状态
			};
		},
		computed: {
			// 计算选中商品数量
			selectedCount() {
				return this.cartList.filter(item => item.checked).length;
			}
		},
		onShow() {
			// 页面显示时更新tabbar状态
			onTabPageShow();
			
			this.nowPage = 0
			this.pages = 1
		          this.isLogin = this.$store.getters.isLogin
			this.loadData();
			
			// #ifdef MP-WEIXIN
			// 微信小程序环境下，确保 tabbar 正确显示当前选中状态
			try {
				const app = getApp();
				if (app && typeof app.getTabBar === 'function' && app.getTabBar()) {
					const tabbar = app.getTabBar();
					tabbar.setData({
						selected: 2 // 购物车页面对应的索引
					});
					tabbar.getCartCount && tabbar.getCartCount();
				}
			} catch (e) {
				console.log('更新购物车页 tabbar 状态失败', e);
			}
			// #endif
		},
		watch: {
			// 显示空白页
			cartList(e) {
				let empty = e.length === 0 ? true: false;
				if(this.empty !== empty){
					this.empty = empty;
				}
			}
		},
		created() {
			this.isLogin = this.$store.getters.isLogin
		},
		methods: {
			//请求数据
			async loadData(type) {
				this.loadingType = 'loading'
				if (this.nowPage >= this.pages) {
					this.loadingType = 'noMore'
					return ;
				}
				
				this.nowPage += 1
				let res = await this.$api.cart.myCartList.get({
					limit: this.limit,
					page: this.nowPage
				})
				
				let list = res.data.data
				let cartList = list.map(item => {
					item.checked = false;
					return item;
				});
			
				if (type == 'more') {
					this.cartList = this.cartList.concat(cartList);
				} else {
					this.pages = Math.ceil(res.data.total / res.data.per_page)
					this.cartList = cartList;
					if (this.pages == this.nowPage) {
						this.showLoad = false;
					}
				}
				this.calcTotal();  // 计算总价
				this.updateCartCount(); // 更新购物车数量
			},
			navToLogin() {
				goLogin()
			},
			navToHome() {
				uni.switchTab({
					url: '../index/index'
				})
			},
			navToProduct(goodsId) {
				uni.navigateTo({
					url: `/pages/product/product?id=${goodsId}`
				})
			},
			 // 选中状态处理
			check(type, index) {
				if (type === 'item') {
					this.cartList[index].checked = !this.cartList[index].checked;
				} else {
					const checked = !this.allChecked
					const list = this.cartList;
					list.forEach(item=>{
						item.checked = checked;
					})
					this.allChecked = checked;
				}
				this.calcTotal(type);
			},
			// 数量
			numberChange(num, index) {
				this.cartList[index].goods_num = num;
				this.changeNum({
					id: this.cartList[index].id,
					num: num
				});
				this.calcTotal();
			},
			// 改变购物车商品数量
			async changeNum(form) {
				await this.$api.cart.changeNum.post(form)
			},
			// 删除
			async deleteCartItem(index) {
				let list = this.cartList;
				let row = list[index];
				let id = row.id;
				
				uni.showModal({
					title: '提示',
					content: '确定要删除这个商品吗？',
					success: async (e) => {
						if (e.confirm) {
							uni.showLoading({
								title: '删除中...'
							})
							
							let res = await this.$api.cart.remove.get({
								id: id
							})
							
							uni.hideLoading();
							
							if (res.code != 0) {
								this.$tool.msg(res.msg);
								return;
							}
							
							this.cartList.splice(index, 1);
							this.calcTotal();
							this.updateCartCount(); // 更新购物车数量
							this.$tool.msg('删除成功');
						}
					}
				})
			},
			// 清空
			clearCart() {
				uni.showModal({
					title: '提示',
					content: '确定要清空购物车吗？',
					success: async (e) => {
						if (e.confirm) {
							uni.showLoading({
								title: '清空中...'
							})
							
							let res = await this.$api.cart.clearCart.get()
							uni.hideLoading();
							
							if (res.code == 0) {
								this.$tool.msg('清空成功')
								this.nowPage = 0
								setTimeout(() => {
									this.loadData()
								}, 800)
								this.updateCartCount(); // 更新购物车数量
							} else {
								this.$tool.msg(res.msg)
							}
						}
					}
				})
			},
			// 计算总价
			calcTotal() {
				let list = this.cartList;
				if (list.length === 0) {
					this.empty = true;
					return;
				}
				
				let total = 0;
				let checked = true;
				list.forEach(item => {
					if (item.checked === true) {
						total += item.price * item.goods_num;
					} else if (checked === true) {
						checked = false;
					}
				})
				this.allChecked = checked;
				this.total = Number(total.toFixed(2));
			},
			// 创建订单
			createOrder() {
				let list = this.cartList;
				let goodsData = [];
				list.forEach(item => {
					if (item.checked) {
						goodsData.push({
							id: item.goods_id,
							cart_id: item.id,
							price: item.price,
							num: item.goods_num,
							rule_id: item.rule_id,
							type: 1
						})
					}
				})
				
				if (goodsData.length == 0) {
					this.$tool.msg('请选择商品')
					return
				}
				
				uni.setStorage({
					key: 'CREATE_ORDER',
					data: JSON.stringify(goodsData)
				})
				
				uni.navigateTo({
					url: `/pages/order/createOrder`
				})
			},
			// 加载更多
			onReachBottom() {
				this.loadData('more')
			},
			// 更新购物车数量
			updateCartCount() {
				// 更新store中的购物车数量
				this.$store.commit('app/UPDATE_CART_COUNT', this.cartList.length);
				
				// 触发自定义tabbar更新 - 使用uni.$emit替代this.$fire.emit
				try {
					uni.$emit('updateCartCount');
				} catch (e) {
					console.log('触发购物车更新事件失败', e);
				}
				
				// #ifdef MP-WEIXIN
				// 小程序环境下更新全局购物车数量
				const app = getApp();
				if (app && app.globalData) {
					app.globalData.cartCount = this.cartList.length;
					// 通知自定义tabbar更新
					if (typeof app.getTabBar === 'function' && app.getTabBar()) {
						app.getTabBar().setData({
							list: app.getTabBar().data.list.map((item, index) => {
								if (index === 2) { // 购物车是第3个tab
									item.badge = this.cartList.length > 0 ? this.cartList.length : null;
								}
								return item;
							})
						});
					}
				}
				// #endif
			},
		}
	}
</script>

<style lang='scss' scoped>

	.container {
		padding-bottom: calc(140upx + 50rpx); /* 减少底部间距避免被自定义tabBar遮挡 */
		min-height: 100vh;
		background: #f4f4f4;
	}
	
	/* 空白页 */
	.empty {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: calc(100vh - 120rpx);
		display: flex;
		align-items: center;
		justify-content: center;
		
		.empty-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 60upx 40upx;
			text-align: center;
		}
		
		.empty-icon {
			margin-bottom: 40upx;
			opacity: 0.8;
			animation: float 3s ease-in-out infinite;
		}
		
		@keyframes float {
			0% { transform: translateY(0px); }
			50% { transform: translateY(-10px); }
			100% { transform: translateY(0px); }
		}
		
		.empty-title {
			font-size: 36upx;
			font-weight: 600;
			color: #333;
			margin-bottom: 16upx;
		}
		
		.empty-subtitle {
			font-size: 28upx;
			color: #999;
			margin-bottom: 60upx;
		}
		
		.empty-actions {
			display: flex;
			justify-content: center;
		}
		
		.empty-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 20upx 40upx;
			border-radius: 50upx;
			font-size: 30upx;
			font-weight: 500;
			transition: all 0.3s ease;
			
			&.primary {
				background: linear-gradient(135deg, #e93323 0%, #ff6b6b 100%);
				color: #fff;
				box-shadow: 0 8upx 20upx rgba(233, 51, 35, 0.3);
				
				&:active {
					transform: translateY(2upx);
					box-shadow: 0 4upx 10upx rgba(233, 51, 35, 0.3);
				}
			}
		}
	}
	
	.cart-content {
		background: #f5f5f5;
	}
	
	/* 购物车头部 */
	.cart-header {
		padding: 30upx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #f0f0f0;
		
		.header-title {
			font-size: 32upx;
			font-weight: 600;
			color: #333;
		}
		
		.header-actions {
			display: flex;
			align-items: center;
			color: #999;
			font-size: 28upx;
			transition: all 0.3s ease;
			
			&:active {
				color: #e93323;
				transform: scale(0.95);
			}
			
			text {
				margin-left: 8upx;
			}
		}
	}
	
	/* 购物车列表 */
	.cart-list {
		padding: 20upx 0;
	}
	
	.cart-item {
		background: #fff;
		margin: 0 30upx 20upx;
		border-radius: 20upx;
		padding: 30upx;
		display: flex;
		align-items: flex-start;
		box-shadow: 0 4upx 20upx rgba(0, 0, 0, 0.04);
		transition: all 0.3s ease;
		position: relative;
		overflow: hidden;
		
		&::before {
			content: '';
			position: absolute;
			left: 0;
			top: 0;
			width: 6upx;
			height: 100%;
			background: transparent;
			transition: all 0.3s ease;
		}
		
		&.checked::before {
			background: linear-gradient(135deg, #e93323 0%, #ff6b6b 100%);
		}
		
		
		&:active {
			transform: scale(0.98);
		}
	}
	
	.item-checkbox {
		margin-right: 20upx;
		padding-top: 10upx;
	}
	
	.checkbox-circle {
		width: 40upx;
		height: 40upx;
		border-radius: 50%;
		border: 2px solid #ddd;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
		
		&.checked {
			background: #e93323;
			border-color: #e93323;
		}
	}
	
	.item-image {
		width: 160upx;
		height: 160upx;
		border-radius: 16upx;
		overflow: hidden;
		margin-right: 20upx;
		position: relative;
		
		.product-img {
			width: 100%;
			height: 100%;
			border-radius: 16upx;
			transition: all 0.3s ease;
		}
		
		&:active .product-img {
			transform: scale(0.95);
		}
	}
	
	.item-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: hidden;
	}
	
	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 16upx;
	}
	
	.item-title {
		font-size: 30upx;
		font-weight: 500;
		color: #333;
		line-height: 1.4;
		flex: 1;
		margin-right: 20upx;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		text-overflow: ellipsis;
		transition: all 0.3s ease;
		
		&:active {
			color: #e93323;
		}
	}
	
	.item-delete {
		width: 40upx;
		height: 40upx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		transition: all 0.3s ease;
		
		&:active {
			background: rgba(233, 51, 35, 0.1);
			transform: scale(0.9);
		}
	}
	
	.item-attrs {
		margin-bottom: 20upx;
		
		.attr-text {
			font-size: 24upx;
			color: #999;
			background: #f5f5f5;
			padding: 8upx 16upx;
			border-radius: 8upx;
			display: inline-block;
		}
	}
	
	.item-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: auto;
	}
	
	.item-price {
		display: flex;
		align-items: baseline;
		
		.price-symbol {
			font-size: 24upx;
			color: #e93323;
			font-weight: 500;
		}
		
		.price-value {
			font-size: 36upx;
			font-weight: 600;
			color: #e93323;
		}
	}
	
	.item-quantity {
		
	}
	
	/* 底部栏 */
	.action-section {
		position: fixed;
		left: 0;
		bottom: calc(50px + 100rpx); /* 调整底部位置避免被自定义tabBar遮挡 */
		z-index: 95;
		display: flex;
		align-items: center;
		width: 100%;
		height: 120upx;
		padding: 0 30upx;
		background: rgba(255, 255, 255, 0.98);
		backdrop-filter: blur(20upx);
		box-shadow: 0 -4upx 20upx rgba(0, 0, 0, 0.05);
	}
	
	.select-all {
		display: flex;
		align-items: center;
		margin-right: 30upx;
		
		.checkbox-circle {
			margin-right: 16upx;
		}
		
		.select-text {
			font-size: 28upx;
			color: #333;
		}
	}
	
	.total-box {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		margin-right: 30upx;
		
		.total-info {
			display: flex;
			align-items: baseline;
			margin-bottom: 8upx;
			
			.total-label {
				font-size: 28upx;
				color: #333;
			}
			
			.total-price {
				display: flex;
				align-items: baseline;
				margin-left: 8upx;
				
				.price-symbol {
					font-size: 24upx;
					color: #e93323;
					font-weight: 500;
				}
				
				.price-value {
					font-size: 40upx;
					font-weight: 600;
					color: #e93323;
				}
			}
		}
		
		.save-info {
			font-size: 24upx;
			color: #999;
		}
	}
	
	.confirm-btn {
		min-width: 200upx;
		height: 80upx;
		line-height: 80upx;
		border-radius: 40upx;
		font-size: 30upx;
		font-weight: 500;
		background: #e93323;
		transition: all 0.3s ease;
		
		&.disabled {
			background: #ccc;
		}
		
		&:not(.disabled):active {
			transform: translateY(2upx);
		}
	}
</style>